import json
import os
import jpype


# jvmPath = jpype.getDefaultJVMPath()
# jpype.startJVM(jvmPath)
# jpype.java.lang.System.out.println("hello world!")
# jpype.shutdownJVM()

def java_class_func(jar_path, class_name, func_name, jvm_path=none, *args):
    """
    调用jar包中class下的方法
    :return:
    """
    # jar包路径的配置
    # jarpath = os.path.join(os.path.abspath("."), "d:\\hf-0.1.jar")
    jarpath = os.path.join(os.path.abspath("../.."), jar_path)
    # 这里指定了jvm
    if jvm_path:
        jvmpath = jvm_path
    else:
        jvmpath = jpype.getdefaultjvmpath()
    jpype.startJVM(jvmpath, "-ea", "-Djava.class.path=%s" % jarpath)

    # 这里是指定哪个class，执行哪个方法，入参和结果展示
    # java_class = jpype.JClass("com.dubbo.testjsf.R2mUtils")
    # java_class.getCustKeys()

    java_class = jpype.JClass(class_name)
    ru_param = ','.join(list(map(lambda x: json.dumps(x), args)))

    ########################################################################
    # 判断是否有中文在里面，有就转成unicode，后来发现是pycharm的编码格式问题，这里就注释了
    # def _iszh(p):
    #     for c in p:
    #         if '\u4e00' <= c <= '\u9fa5':
    #             return True
    #     return False
    #
    # args_list = list(map(lambda x: json.dumps(x) if _iszh(x) else x, args))
    ########################################################################

    res = eval("java_class.%s(%s)" % (func_name, ru_param))
    print(res)  # 打印有返回值方法的结果
    jpype.shutdownJVM()


if __name__ == '__main__':

    java_class_func(r"/Users/zhihao.lin/IdeaProjects/ad-d-hawking-spark/target/ad-d-hawking-spark-EU-1.0-SNAPSHOT.jar",
                    "nio.com.utils.StringUtil",
                    "lowerCaseFirst",
                    "/Library/Java/JavaVirtualMachines/jdk1.8.0_202.jdk/Contents/Home/jre/lib/server/libjvm.dylib",
                    "Lzhcode")
